import 'package:flutter/material.dart';

///一个自定义的手写笔迹视图，
///1.每次鼠标按下到鼠标抬起为一个笔画，分别记录所有的笔画
///2.绘制出所有笔画

class HandwritingView extends StatefulWidget {
  const HandwritingView({super.key});

  @override
  HandwritingViewState createState() => HandwritingViewState();
}

class HandwritingViewState extends State<HandwritingView> {
  //存储笔画点集
  final List<List<Offset>> _strokes = [];

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanStart: (details) {
        setState(() {
          //点击事件开始，生成一个新的笔画List
          _strokes.add([details.localPosition]);
        });
      },
      onPanUpdate: (details) {
        setState(() {
          //移动时，将点集加入到最新的那个笔画List
          _strokes.last.add(details.localPosition);
        });
      },
      onPanEnd: (details) {
        setState(() {
        });
      },
      //使用Canvas绘制点集
      child: CustomPaint(
        painter: HandwritingPainter(_strokes),
      ),
    );
  }
}

class HandwritingPainter extends CustomPainter {
  final List<List<Offset>> strokes;

  HandwritingPainter(this.strokes);

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawColor(Colors.blue,BlendMode.color);
    final paint = Paint()
      ..color = Colors.black
      ..strokeWidth = 3.0
      ..strokeCap = StrokeCap.round
      ..style = PaintingStyle.stroke;

    //使用drawLine绘制直线导致笔画看起来不够平滑，请使用贝塞尔曲线绘制笔画
    for (final stroke in strokes) {
      final path = Path();
      path.moveTo(stroke.first.dx, stroke.first.dy);
      for (var i = 0; i < stroke.length - 1; i++) {
        final p1 = stroke[i];
        final p2 = stroke[i + 1];
        final midPoint = Offset((p1.dx + p2.dx) / 2, (p1.dy + p2.dy) / 2);
        path.quadraticBezierTo(p1.dx, p1.dy, midPoint.dx, midPoint.dy);
      }
      canvas.drawPath(path, paint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
